# Maintainer: Andrew Sun <adsun701@gmail.com>

_realname=ptex
pkgbase=mingw-w64-${_realname}
pkgname=(
  "${MINGW_PACKAGE_PREFIX}-${_realname}"
  "${MINGW_PACKAGE_PREFIX}-${_realname}-docs"
)
pkgver=2.4.3
pkgrel=1
pkgdesc="Per-Face Texture Mapping for Production Rendering (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url='https://ptex.us/'
msys2_references=(
  "cpe: cpe:/a:disneyanimation:ptex"
)
license=('spdx:BSD-3-Clause')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-libwinpthread"
         "${MINGW_PACKAGE_PREFIX}-zlib")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-pkgconf"
             "${MINGW_PACKAGE_PREFIX}-doxygen")
source=("https://github.com/wdas/${_realname}/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz"
        "0001-ptex-2.1.28-remove-msc_ver.patch"
        "0002-ptex-2.1.28-install-dll-correctly.patch"
        "0004-mingw-isfinite.patch")
sha256sums=('435aa2ee1781ff24859bd282b7616bfaeb86ca10604b13d085ada8aa7602ad27'
            'a0ee8547873a24bbe57a799a5cd895e91b786a926c8c3dba5d0771cca8c2d0a3'
            '1c6f78a9cb1eb790abaee2e43802a037b92abf9b41d54a6eb8a82f0d1a50457a'
            '2ffad92e3dae6647a5ae4dc7f4b1ad77297495fbf70825f86ea6490c884822f9')

# Helper macros to help make tasks easier #
apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  cd "${srcdir}"/${_realname}-${pkgver}
  apply_patch_with_msg \
    0001-ptex-2.1.28-remove-msc_ver.patch \
    0002-ptex-2.1.28-install-dll-correctly.patch \
    0004-mingw-isfinite.patch

  cd src/doc
  ${MINGW_PREFIX}/bin/doxygen -u
}

build() {
  mkdir -p "${srcdir}"/build-${MSYSTEM} && cd "${srcdir}"/build-${MSYSTEM}

  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    ${MINGW_PREFIX}/bin/cmake \
      -G'Ninja' \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      "${extra_config[@]}" \
      -DPTEX_BUILD_SHARED_LIBS=ON \
      -DPTEX_BUILD_STATIC_LIBS=ON \
      ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake --build .
}

package_ptex() {
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install "build-${MSYSTEM}"

  # split docs
  mkdir -p dest${MINGW_PREFIX}/share
  mv "${pkgdir}${MINGW_PREFIX}"/share/doc dest${MINGW_PREFIX}/share/doc
}

package_ptex-docs() {
  pkgdesc+=" (documentation)"
  depends=()

  mv dest/* "${pkgdir}"
}

# template start; name=mingw-w64-splitpkg-wrappers; version=1.0;
# vim: set ft=bash :

# generate wrappers
for _name in "${pkgname[@]}"; do
  _short="package_${_name#${MINGW_PACKAGE_PREFIX}-}"
  _func="$(declare -f "${_short}")"
  eval "${_func/#${_short}/package_${_name}}"
done
# template end;
